import { lazyReport } from "./report.js";
import { ERROR, PROMISE_ERROR, JS_ERROR, RESOURCE_ERROR } from "./constants.js";
import { getPathTo } from "./utils.js";
/*
 * 全局错误捕获
 */
export const errorTrackerReport = () => {
  // promise error
  window.addEventListener("unhandledrejection", (error) => {
    const { reason } = error;
    const errorPage = window.location.href;
    lazyReport({
      type: ERROR,
      data: {
        category: PROMISE_ERROR,
        errorPage,
        errorData: error,
      },
    });
  });
  // js error
  const originOnError = window.onerror;
  window.onerror = (msg, url, row, col, error) => {
    const errorPage = window.location.href;
    if (originOnError) {
      // 项目中如果使用了onerror方法应处理原有的onerror
      originOnError.call(window, msg, url, row, col, error);
    }
    lazyReport({
      type: ERROR,
      data: {
        category: JS_ERROR,
        errorPage,
        errorData: { msg, url, row, col, error },
      },
    });
  };

  // resource error
  window.addEventListener(
    "error",
    (error) => {
      const errorPage = window.location.href;
      const { target } = error;
      const elementList = [
        "HTMLScriptElement",
        "HTMLLinkElement",
        "HTMLImageElement",
      ];
      const isElement = elementList.find(
        (element) => target instanceof window[element]
      );
      // const isElement = target instanceof HTMLScriptElement || target instanceof HTMLLinkElement || target instanceof HTMLImageElement;
      if (!isElement) return; // js的错误此处不应再处理，否则重复
      lazyReport({
        type: ERROR,
        data: {
          category: RESOURCE_ERROR,
          errorPage,
          errorData: target,
          path: getPathTo(target),
        },
      });
    },
    true
  );
};
export default { errorTrackerReport };
